package cn.geminis.resources.service.controller;

import cn.geminis.auth.context.LoginUser;
import cn.geminis.resources.service.model.OrgUser;
import cn.geminis.resources.service.model.Role;
import cn.geminis.resources.service.model.User;
import cn.geminis.resources.service.model.filter.UserFilter;
import cn.geminis.resources.service.model.repository.OrganizationRepository;
import cn.geminis.resources.service.model.repository.RoleRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;

/**
 * @author Allen
 */
public class UserController {

    private final RoleRepository roleRepository;
    private final OrganizationRepository organizationRepository;

    @PutMapping("/{id}/role")
    public void setRoles(@PathVariable String id, @RequestBody List<String> roles) {
        var user = this.repository.findOne(
                        UserFilter.builder()
//                                .include(new String[]{"riles"})
                                .id(id)
                                .build()
                )
                .orElseThrow(() -> new RuntimeException("用户不存在：" + id));
        var rs = this.roleRepository.findAllById(roles);

        user.setRoles(new HashSet<>(rs));
        this.repository.save(user);
    }

    @GetMapping("/{id}/role/name")
    public List<String> userRoleName(@PathVariable String id) {
        return this.repository.findOne(
                        UserFilter.builder()
                                .include(new String[]{"roles"})
                                .id(id)
                                .build()
                )
                .get()
                .getRoles()
                .stream()
                .map(Role::getName)
                .toList();
    }

    @PostMapping("/{userId}/org/{orgId}/{type}")
    @Transactional
    public void addToOrg(@PathVariable String userId,
                         @PathVariable String orgId,
                         @PathVariable String type) {

        var org = this.organizationRepository.findById(orgId).get();
        var user = this.repository.findById(userId).get();

        var orgUser = new OrgUser();
        orgUser.setOrganization(org);
        orgUser.setUser(user);
        orgUser.setType(type);
        user.getOrganizations().clear();
        user.getOrganizations().add(orgUser);

        this.repository.save(user);
    }

    @GetMapping("/my")
    public User loginUserInfo() {
        return this.repository.findOne(
                        UserFilter.builder()
                                .include(new String[]{"roles"})
                                .id(LoginUser.userId())
                                .build()
                )
                .get();
    }

}
